package com.lgy.converter;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lgy.beans.OrderDetail;
import com.lgy.dto.OrderDTO;
import com.lgy.enums.ResultEnum;
import com.lgy.exception.SellException;
import com.lgy.form.OrderForm;

import java.util.List;

public class OrderFormToOrderDTOConverter {

    public static OrderDTO convert(OrderForm orderForm) throws SellException {
        Gson gson = new Gson();

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        List<OrderDetail> orderDetailList;
        try {
            // 将字符串转成List<OrderDetail>
            orderDetailList = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>(){}.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

}
